#include "Ctrl_Reg_Driver_App.h"

static int Ctrl_Reg_Driver_Num=0;

int Init_Ctrl_Reg_Driver(void)
{
    Ctrl_Reg_Driver_Num = open(Ctrl_Reg_Driver_Name, O_RDWR);
	if(Ctrl_Reg_Driver_Num < 0){
		printf("Ctrl_Reg_Driver open failed!\r\n");
	}
    return Ctrl_Reg_Driver_Num;
}

int Close_Ctrl_Reg_Driver(void)
{
    int retvalue = close(Ctrl_Reg_Driver_Num); /* 关闭文件 */
	if(retvalue < 0){
		printf("Ctrl_Reg_Driver close failed!\r\n");
	}
    return retvalue;
}

Ctrl_Reg_Driver_Struct Ctrl_Reg_Driver_Read(Ctrl_Reg_Driver_Struct Stu)
{
    uint8_t databuf[4];
    uint32_t val=0;
    int retvalue = lseek(Ctrl_Reg_Driver_Num,Stu.ADDR,0);
    if(retvalue < 0){
		printf("Ctrl_Reg_Driver lseek failed!\r\n");
        Close_Ctrl_Reg_Driver();
        Stu.Error_Flag=-2;
		return Stu;
	}

    retvalue = read(Ctrl_Reg_Driver_Num, &databuf[0], 1);
	if(retvalue < 0){
		printf("Ctrl_Reg_Driver Read Failed!\r\n");
		Close_Ctrl_Reg_Driver();
        Stu.Error_Flag=-1;
		return Stu;
	}

    memcpy(&val,&databuf[0],4);
    Stu.Value=val;
    Stu.Error_Flag=0;
    return Stu;
}

Ctrl_Reg_Driver_Struct Ctrl_Reg_Driver_Write(Ctrl_Reg_Driver_Struct Stu)
{
    uint8_t databuf[4];
    uint32_t val = Stu.Value;
    int retvalue = lseek(Ctrl_Reg_Driver_Num,Stu.ADDR,0);
    if(retvalue < 0){
		printf("Ctrl_Reg_Driver lseek failed!\r\n");
        Close_Ctrl_Reg_Driver();
        Stu.Error_Flag=-2;
		return Stu;
	}

    memcpy(&databuf[0],&val,4);
    retvalue = write(Ctrl_Reg_Driver_Num, &databuf[0], 1);
	if(retvalue < 0){
		printf("Ctrl_Reg_Driver Write Failed!\r\n");
		Close_Ctrl_Reg_Driver();
        Stu.Error_Flag=-1;
		return Stu;
	}

    Stu.Error_Flag=0;
    return Stu;
}
